<template>
  <div class="customer-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
    </div>

    <!-- 查询条件 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="护理等级">
          <el-select
            v-model="searchForm.careLevel"
            placeholder="请选择护理等级"
            clearable
            style="width: 150px"
          >
            <el-option label="一级护理" value="LEVEL_1" />
            <el-option label="二级护理" value="LEVEL_2" />
            <el-option label="三级护理" value="LEVEL_3" />
            <el-option label="特级护理" value="SPECIAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.gender"
            placeholder="请选择性别"
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="在院" value="ACTIVE" />
            <el-option label="出院" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增客户
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 客户表格 -->
    <el-table
      v-loading="loading"
      :data="customerList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          <el-tag :type="row.gender === 'MALE' ? 'primary' : 'danger'">
            {{ row.gender === 'MALE' ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" width="130" />
      <el-table-column prop="careLevel" label="护理等级" width="100">
        <template #default="{ row }">
          <el-tag :type="getCareLevelTagType(row.careLevel)">
            {{ getCareLevelText(row.careLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roomNumber" label="房间号" width="100" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">
            {{ row.status === 'ACTIVE' ? '在院' : '出院' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="admissionDate" label="入院日期" width="120" />
      <el-table-column prop="emergencyContact" label="紧急联系人" width="120" />
      <el-table-column prop="emergencyPhone" label="紧急联系电话" width="130" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="info" size="small" @click="handleView(row)">
            详情
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 客户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="customerFormRef"
        :model="customerForm"
        :rules="customerRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="customerForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="customerForm.age"
                :min="0"
                :max="150"
                placeholder="请输入年龄"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="customerForm.gender">
                <el-radio value="MALE">男</el-radio>
                <el-radio value="FEMALE">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="customerForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="护理等级" prop="careLevel">
              <el-select v-model="customerForm.careLevel" placeholder="请选择护理等级" style="width: 100%">
                <el-option label="一级护理" value="LEVEL_1" />
                <el-option label="二级护理" value="LEVEL_2" />
                <el-option label="三级护理" value="LEVEL_3" />
                <el-option label="特级护理" value="SPECIAL" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="customerForm.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入院日期" prop="admissionDate">
              <el-date-picker
                v-model="customerForm.admissionDate"
                type="date"
                placeholder="请选择入院日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="customerForm.status">
                <el-radio value="ACTIVE">在院</el-radio>
                <el-radio value="INACTIVE">出院</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="customerForm.emergencyContact" placeholder="请输入紧急联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系电话" prop="emergencyPhone">
              <el-input v-model="customerForm.emergencyPhone" placeholder="请输入紧急联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="医疗信息">
          <el-input
            v-model="customerForm.medicalInfo"
            type="textarea"
            :rows="3"
            placeholder="请输入医疗信息（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getCustomerList,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  batchDeleteCustomers
} from '@/api/customer'

// 响应式数据
const loading = ref(false)
const customerList = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const customerFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  careLevel: '',
  gender: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 客户表单
const customerForm = reactive({
  id: null,
  name: '',
  age: null,
  gender: '',
  phone: '',
  careLevel: '',
  roomNumber: '',
  admissionDate: '',
  status: 'ACTIVE',
  emergencyContact: '',
  emergencyPhone: '',
  medicalInfo: ''
})

// 表单验证规则
const customerRules = {
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 0, max: 150, message: '年龄必须在0-150之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  careLevel: [
    { required: true, message: '请选择护理等级', trigger: 'change' }
  ],
  roomNumber: [
    { required: true, message: '请输入房间号', trigger: 'blur' }
  ],
  admissionDate: [
    { required: true, message: '请选择入院日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' }
  ],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取客户列表
const fetchCustomerList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    const response = await getCustomerList(params)
    customerList.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchCustomerList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    careLevel: '',
    gender: '',
    status: ''
  })
  pagination.page = 1
  fetchCustomerList()
}

// 新增客户
const handleAdd = () => {
  dialogTitle.value = '新增客户'
  resetCustomerForm()
  dialogVisible.value = true
}

// 编辑客户
const handleEdit = (row) => {
  dialogTitle.value = '编辑客户'
  Object.assign(customerForm, { ...row })
  dialogVisible.value = true
}

// 查看客户详情
const handleView = (row) => {
  // 这里可以跳转到详情页面或显示详情对话框
  ElMessage.info('查看客户详情功能待实现')
}

// 删除客户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteCustomer(row.id)
    ElMessage.success('删除成功')
    fetchCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个客户吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await batchDeleteCustomers(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    fetchCustomerList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchCustomerList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchCustomerList()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await customerFormRef.value.validate()
    if (customerForm.id) {
      await updateCustomer(customerForm.id, customerForm)
      ElMessage.success('更新成功')
    } else {
      await createCustomer(customerForm)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchCustomerList()
  } catch (error) {
    if (error.message) {
      ElMessage.error('操作失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  customerFormRef.value?.resetFields()
  resetCustomerForm()
}

// 重置客户表单
const resetCustomerForm = () => {
  Object.assign(customerForm, {
    id: null,
    name: '',
    age: null,
    gender: '',
    phone: '',
    careLevel: '',
    roomNumber: '',
    admissionDate: '',
    status: 'ACTIVE',
    emergencyContact: '',
    emergencyPhone: '',
    medicalInfo: ''
  })
}

// 获取护理等级标签类型
const getCareLevelTagType = (careLevel) => {
  const levelMap = {
    SPECIAL: 'danger',
    LEVEL_1: 'warning',
    LEVEL_2: 'primary',
    LEVEL_3: 'success'
  }
  return levelMap[careLevel] || 'info'
}

// 获取护理等级文本
const getCareLevelText = (careLevel) => {
  const levelMap = {
    SPECIAL: '特级护理',
    LEVEL_1: '一级护理',
    LEVEL_2: '二级护理',
    LEVEL_3: '三级护理'
  }
  return levelMap[careLevel] || careLevel
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCustomerList()
})
</script>

<style scoped>
.customer-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>